# coding=utf-8

import csv
import os.path
# headers = ['class','name','sex','height','year']
#
# rows = [
#         {'class':1,'name':'xiaoming','sex':'male','height':168,'year':23},
#         {'class':1,'name':'xiaohong','sex':'female','height':162,'year':22},
#         {'class':2,'name':'xiaozhang','sex':'female','height':163,'year':21},
#         {'class':2,'name':'xiaoli','sex':'male','height':158,'year':21},
#     ]
#
# with open('test2.csv','w',newline='')as f:
#     f_csv = csv.DictWriter(f,headers)
#     f_csv.writeheader()
#     f_csv.writerows(rows)

class ReadWriterCSV(object):

    def __init__(self, csvfile):
        self.csvfile = csvfile

    def print_csvfile(self):
        print("csvfile is %s" % self.csvfile)

    def getPath(self):
        # "../ testcase / testcase_addcustomer.csv"
        dir = os.path.dirname(os.path.abspath('.'))
        path = dir + "/testcase/" + self.csvfile

        print("path is %s " % path)
        return path

    def csv_read(self):

        data = []
        path = self.getPath()
        with open(path, 'r', encoding='utf-8') as f:
            reader = csv.reader(f, dialect='excel')
            for row in reader:
                data.append(row)
            return data

    def csv_dict_read(self):
        data = []
        path = self.getPath()
        with open(path, 'r+', encoding='utf-8') as f:

            dict_reader = csv.DictReader(f, dialect='excel')

            # fieldnames 方法打印出列名
            # print("fieldnames is %s" % dict_reader.fieldnames, end="\n")
            for row in dict_reader:
                # 打印出指定的列名的值
                # print("row['test_data'] is %s" % row['test_data'],end="\n")
                # 打印出字典格式的每一行的列值，格式：[(key1，value1),(key2，value2),...]
                # print("row is %s" % row)
                dRow = {}
                for k, v in row.items():
                    dRow[k] = v
                data.append(dRow)
            return data


    # def csv_writer(self):
    #     path = self.get_path(self)
    #     with open(path, 'w', encoding='utf-8', newline='') as f:
    #         writer = csv.DictWriter(f, head)
    #         writer.writeheader()
    #         writer.writerows(data)
    #         return True

    def csv_dict_write(self, head, data):
        path = self.get_path(self)
        with open(path, 'w', encoding='utf-8', newline='') as f:
            writer = csv.DictWriter(f, head)
            writer.writeheader()
            writer.writerows(data)
            return True


